package com.test.dao;

import com.test.model.Employee;
import com.test.utils.DBUtil;
import com.test.utils.UUIDUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public class EmployeeDaoImpl implements EmployeeDao {


    @Override
    public List<Employee> selctEmployeeList(String name,String salary,String salary2)  throws Exception {
        List<Employee>  employeeList = new ArrayList<Employee>();
        String sql =  "select   * from  employee";
        String str  = "";
        if(  !"".equals(name) &&   name!=null  ){
            str=" where name  like  '%"+name+"%'";
        }
        if( !"".equals(salary)  &&salary !=null ){
            if(str.length()>0){
                str+=" and  salary >"+salary;
            }else{
                str+=" where  salary >"+salary;
            }
        }
        if(    !"".equals(salary2) && salary2 !=null  ){
            if(str.length()>0){
                str+="and salary  <"+salary2;
            }else{
                str+=" where  salary <"+salary2;
            }
        }
        //1.获取jdbc连接
       Connection  connection  = DBUtil.getInstance().getConnection();
        //2.执行sql
        PreparedStatement ps =  connection.prepareStatement(sql+str);
        ResultSet rs = ps.executeQuery();
        if(rs !=  null){
            //3.遍历结果 封装到对象属性上去
            while(rs.next()){
                Employee  employee =   new Employee();
                employee.setId(rs.getString("id"));
                employee.setName(rs.getString("name"));
                employee.setGender(rs.getString("gender"));
                employee.setBirthday(new  java.util.Date(rs.getDate("birthday").getTime()));
                employee.setEmail(rs.getString("email"));
                employee.setSalary(rs.getString("salary"));
                employee.setRemark(rs.getString("remark"));
                //4.将每个封装好了的 对象添加到list里面去
                employeeList.add(employee);
            }
        }
        //5.返回 这个list
        return employeeList;
    }

    /**
     * 新增
     * @param employee
     * @throws Exception
     */
    @Override
    public int insert(Employee emp) throws Exception {
        //1.获取连接对象
        Connection  connection  = DBUtil.getInstance().getConnection();

        //2.执行sql
        String sql = "insert into employee(id,name,gender,birthday,email,salary,remark) values(?,?,?,?,?,?,?)" ;
        PreparedStatement ps = connection.prepareStatement(sql);
        ps.setString(1, emp.getId());
        ps.setString(2, emp.getName());
        ps.setString(3, emp.getGender());
        ps.setDate(4,new java.sql.Date(emp.getBirthday().getTime()) );
        ps.setString(5, emp.getEmail());
        ps.setString(6, emp.getSalary());
        ps.setString(7, emp.getRemark());
        System.out.println(sql);
       return ps.executeUpdate();//执行之前预编译的sql

    }
}
